<template>
	<view class="page-container" :class="themeClass">
		<!-- 自定义导航栏 -->
		<view class="nav-bar">
			<view class="nav-content">
				<text class="nav-title">每日记</text>
				<view class="nav-right" @click="goToSearch">
					<text class="search-icon">🔍</text>
				</view>
			</view>
		</view>
		
		<!-- 页面内容 -->
		<view class="page-content">
			<!-- 用户信息卡片 -->
			<view class="user-card" v-if="userStore.isLogin">
				<view class="user-row">
					<view class="user-left">
						<image 
							class="avatar" 
							:src="userStore.avatar" 
							mode="aspectFill"
						></image>
						<view class="user-info">
							<text class="username">{{ userStore.username }}</text>
							<text class="greeting">{{ greeting }}</text>
						</view>
					</view>
					<view class="stats">
						<text class="stats-number">{{ todayDiaryCount }}</text>
						<text class="stats-label">今日日记</text>
					</view>
				</view>
			</view>
			
			<!-- 未登录状态 -->
			<view class="login-prompt" v-else>
				<text class="prompt-text">开始记录你的美好时光</text>
				<button class="login-btn" @click="goToLogin">立即登录</button>
			</view>
			
			<!-- 快速操作 -->
			<view class="quick-actions">
				<view class="section-title">
					<text class="title-text">快速操作</text>
				</view>
				<view class="actions-grid">
					<view class="action-item" @click="goToWrite">
						<view class="action-icon bg-primary">
							<text class="icon-text">✏️</text>
						</view>
						<text class="action-text">写日记</text>
					</view>
					<view class="action-item" @click="goToDiaryList">
						<view class="action-icon bg-success">
							<text class="icon-text">📖</text>
						</view>
						<text class="action-text">查看日记</text>
					</view>
					<view class="action-item" @click="goToCategory">
						<view class="action-icon bg-warning">
							<text class="icon-text">📂</text>
						</view>
						<text class="action-text">分类管理</text>
					</view>
					<view class="action-item" @click="goToStatistics">
						<view class="action-icon bg-error">
							<text class="icon-text">📊</text>
						</view>
						<text class="action-text">统计分析</text>
					</view>
				</view>
			</view>
			
			<!-- 最近日记 -->
			<view class="recent-diaries" v-if="userStore.isLogin">
				<view class="section-header">
					<text class="title-text">最近日记</text>
					<text class="more-text" @click="goToDiaryList">查看更多</text>
				</view>
				
				<!-- 日记列表 -->
				<view class="diary-list" v-if="recentDiaries.length > 0">
					<view 
						class="diary-item" 
						v-for="diary in recentDiaries" 
						:key="diary.id"
						@click="goToDiaryDetail(diary.id)"
					>
						<view class="diary-header">
							<text class="diary-title">{{ diary.title }}</text>
							<text class="diary-date">{{ formatDate(diary.diaryDate) }}</text>
						</view>
						<text class="diary-content">{{ diary.content }}</text>
						<view class="diary-footer" v-if="diary.mood || diary.weather">
							<view class="diary-meta">
								<text class="meta-item" v-if="diary.mood">{{ diary.mood }}</text>
								<text class="meta-item" v-if="diary.weather">{{ diary.weather }}</text>
							</view>
							<text class="relative-time">{{ getRelativeTime(diary.createdAt) }}</text>
						</view>
					</view>
				</view>
				
				<!-- 空状态 -->
				<view class="empty-state" v-else>
					<text class="empty-icon">📝</text>
					<text class="empty-text">还没有日记</text>
					<button class="empty-btn" @click="goToWrite">开始写日记</button>
				</view>
			</view>
		</view>
		
		<!-- 底部导航栏 -->
		<TabBar :current="0" />
	</view>
</template>

<script>
import { useUserStore } from '@/store/user'
import { useDiaryStore } from '@/store/diary'
import { getDiariesAPI } from '@/api/diary'
import { formatDate, getRelativeTime, formatDateTime } from '@/utils/index'
import TabBar from '@/components/TabBar.vue'
import { extractResponseData } from '@/utils/index'

export default {
	name: 'IndexPage',
	components: {
		TabBar
	},
	setup() {
		const userStore = useUserStore()
		const diaryStore = useDiaryStore()
		
		return {
			userStore,
			diaryStore,
			formatDate,
			getRelativeTime,
			formatDateTime,
			extractResponseData
		}
	},
	data() {
		return {
			recentDiaries: [],
			todayDiaryCount: 0,
			isRefreshing: false
		}
	},
	computed: {
		greeting() {
			const hour = new Date().getHours()
			if (hour < 6) return '夜深了，早点休息'
			if (hour < 12) return '早上好'
			if (hour < 18) return '下午好'
			return '晚上好'
		},
		
		themeClass() {
			return this.userStore.themeMode === 'dark' ? 'theme-dark' : 'theme-light'
		}
	},
	onLoad() {
		this.initPage()
	},
	onShow() {
		// 只有在登录状态下且数据为空时才刷新
		if (this.userStore.isLogin && this.recentDiaries.length === 0) {
			this.refreshData()
		}
	},
	onPullDownRefresh() {
		this.refreshData().finally(() => {
			uni.stopPullDownRefresh()
		})
	},
	methods: {
		async initPage() {
			// 刷新数据
			await this.refreshData()
		},
		
		async refreshData() {
			if (!this.userStore.isLogin || this.isRefreshing) return
			
			this.isRefreshing = true
			
			try {
				// 获取最近的日记
				const res = await getDiariesAPI({
					page: 1,
					limit: 3,
					sortBy: 'created_at',
					sortOrder: 'desc'
				})
				
				const responseData = extractResponseData(res)
				this.recentDiaries = responseData.diaries || []
				
				// 获取今日日记数量
				const today = new Date().toISOString().split('T')[0]
				const todayRes = await getDiariesAPI({
					startDate: today,
					endDate: today
				})
				
				const todayData = extractResponseData(todayRes)
				this.todayDiaryCount = todayData.pagination?.total || 0
			} catch (error) {
				console.error('获取数据失败:', error)
				uni.showToast({
					title: '数据加载失败',
					icon: 'none'
				})
			} finally {
				this.isRefreshing = false
			}
		},
		
		goToLogin() {
			uni.navigateTo({
				url: '/pages/login/login'
			})
		},
		
		goToSearch() {
			uni.navigateTo({
				url: '/pages/search/index'
			})
		},
		
		goToWrite() {
			if (!this.userStore.checkLoginStatus()) return
			uni.switchTab({
				url: '/pages/diary/edit'
			})
		},
		
		goToDiaryList() {
			if (!this.userStore.checkLoginStatus()) return
			uni.switchTab({
				url: '/pages/diary/list'
			})
		},
		
		goToCategory() {
			if (!this.userStore.checkLoginStatus()) return
			uni.switchTab({
				url: '/pages/category/list'
			})
		},
		
		goToStatistics() {
			if (!this.userStore.checkLoginStatus()) return
			uni.navigateTo({
				url: '/pages/statistics/index'
			})
		},
		
		goToDiaryDetail(id) {
			uni.navigateTo({
				url: `/pages/diary/detail?id=${id}`
			})
		}
	}
}
</script>

<style scoped>
.page-container {
	min-height: 100vh;
	background-color: #f5f5f5;
}

.nav-bar {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	z-index: 1000;
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
	padding-top: var(--status-bar-height, 44rpx);
}

.nav-content {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 24rpx 40rpx;
	height: 88rpx;
}

.nav-title {
	font-size: 36rpx;
	font-weight: bold;
	color: #ffffff;
}

.nav-right {
	padding: 8rpx;
}

.search-icon {
	font-size: 32rpx;
	color: #ffffff;
}

.page-content {
	padding-top: calc(var(--status-bar-height, 44rpx) + 88rpx + 40rpx);
	padding-left: 40rpx;
	padding-right: 40rpx;
	padding-bottom: 160rpx;
}

.user-card {
	background-color: #ffffff;
	border-radius: 24rpx;
	padding: 40rpx;
	margin-bottom: 40rpx;
	box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
}

.user-row {
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.user-left {
	display: flex;
	align-items: center;
	flex: 1;
}

.avatar {
	width: 120rpx;
	height: 120rpx;
	border-radius: 60rpx;
	margin-right: 24rpx;
}

.user-info {
	display: flex;
	flex-direction: column;
}

.username {
	font-size: 32rpx;
	font-weight: bold;
	color: #333333;
	margin-bottom: 8rpx;
}

.greeting {
	font-size: 26rpx;
	color: #666666;
}

.stats {
	display: flex;
	flex-direction: column;
	align-items: center;
}

.stats-number {
	font-size: 48rpx;
	font-weight: bold;
	color: #1890ff;
	margin-bottom: 8rpx;
}

.stats-label {
	font-size: 24rpx;
	color: #666666;
}

.login-prompt {
	background-color: #ffffff;
	border-radius: 24rpx;
	padding: 80rpx 40rpx;
	margin-bottom: 40rpx;
	text-align: center;
	box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
}

.prompt-text {
	font-size: 32rpx;
	color: #666666;
	margin-bottom: 40rpx;
	display: block;
}

.login-btn {
	background-color: #1890ff;
	color: #ffffff;
	border: none;
	border-radius: 40rpx;
	padding: 24rpx 48rpx;
	font-size: 28rpx;
}

.login-btn::after {
	border: none;
}

.quick-actions {
	margin-bottom: 40rpx;
}

.section-title {
	margin-bottom: 24rpx;
}

.section-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 24rpx;
}

.title-text {
	font-size: 32rpx;
	font-weight: bold;
	color: #333333;
}

.more-text {
	font-size: 26rpx;
	color: #1890ff;
}

.actions-grid {
	display: grid;
	grid-template-columns: repeat(4, 1fr);
	gap: 32rpx;
}

.action-item {
	display: flex;
	flex-direction: column;
	align-items: center;
	text-align: center;
}

.action-icon {
	width: 120rpx;
	height: 120rpx;
	border-radius: 24rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	margin-bottom: 16rpx;
}

.bg-primary {
	background-color: #1890ff;
}

.bg-success {
	background-color: #52c41a;
}

.bg-warning {
	background-color: #faad14;
}

.bg-error {
	background-color: #ff4d4f;
}

.icon-text {
	font-size: 48rpx;
}

.action-text {
	font-size: 24rpx;
	color: #666666;
}

.recent-diaries {
	margin-bottom: 40rpx;
}

.diary-list {
	display: flex;
	flex-direction: column;
	gap: 24rpx;
}

.diary-item {
	background-color: #ffffff;
	border-radius: 16rpx;
	padding: 32rpx;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
	transition: transform 0.2s;
}

.diary-item:active {
	transform: scale(0.98);
}

.diary-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 16rpx;
}

.diary-title {
	font-size: 28rpx;
	font-weight: 500;
	color: #333333;
	flex: 1;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
	margin-right: 16rpx;
}

.diary-date {
	font-size: 24rpx;
	color: #666666;
}

.diary-content {
	font-size: 26rpx;
	color: #666666;
	line-height: 1.6;
	margin-bottom: 16rpx;
	display: -webkit-box;
	-webkit-line-clamp: 2;
	-webkit-box-orient: vertical;
	overflow: hidden;
}

.diary-footer {
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.diary-meta {
	display: flex;
	gap: 16rpx;
}

.meta-item {
	background-color: #f0f0f0;
	color: #666666;
	padding: 8rpx 16rpx;
	border-radius: 16rpx;
	font-size: 22rpx;
}

.relative-time {
	font-size: 22rpx;
	color: #999999;
}

.empty-state {
	text-align: center;
	padding: 80rpx 40rpx;
}

.empty-icon {
	font-size: 120rpx;
	margin-bottom: 24rpx;
	display: block;
}

.empty-text {
	font-size: 28rpx;
	color: #666666;
	margin-bottom: 40rpx;
	display: block;
}

.empty-btn {
	background-color: #1890ff;
	color: #ffffff;
	border: none;
	border-radius: 40rpx;
	padding: 24rpx 48rpx;
	font-size: 28rpx;
}

.empty-btn::after {
	border: none;
}

/* 主题适配 */
.theme-light.page-container {
	background-color: #f5f5f5 !important;
}

.theme-dark.page-container {
	background-color: #1e1e1e !important;
}

.theme-dark .nav-bar {
	background: linear-gradient(135deg, #404040 0%, #2d2d30 100%);
}

.theme-dark .user-card,
.theme-dark .login-prompt,
.theme-dark .diary-item {
	background-color: #252526;
}

.theme-dark .username,
.theme-dark .title-text,
.theme-dark .diary-title {
	color: #e8e8e8;
}

.theme-dark .greeting,
.theme-dark .stats-label,
.theme-dark .prompt-text,
.theme-dark .action-text,
.theme-dark .diary-date,
.theme-dark .diary-content,
.theme-dark .empty-text {
	color: #b3b3b3;
}

.theme-dark .meta-item {
	background-color: #404040;
	color: #b3b3b3;
}

.theme-dark .relative-time {
	color: #8c8c8c;
}
</style>
